package com.all.websocket.annotation.handler;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author LY
 * @create 2024/2/29 16:59
 * @Description WebSocket
 */
@Component
@ServerEndpoint("/connect/{info}")
public class WebSocketHandler {

    @OnOpen
    public void onOpen(Session session, @PathParam("info") String info){
        System.out.println("【websocket连接成功】");
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("【websocket退出成功】");
    }

    @OnError
    public void onError(Session session, Throwable throwable) throws IOException {
        System.out.println("【websocket异常】");
        throwable.printStackTrace();
        session.close();
    }

    @OnMessage
    public void onMessage(Session session, String message){
        System.out.println("【websocket接收成功】收到客户端发来的消息：" + message);
        // 异步发送
        session.getAsyncRemote().sendText(fakeAi(message));
    }

    private static String fakeAi(String input) {
        if (input == null || "".equals(input)) {
            return "你说什么？没听清︎";
        }
        return input.replace('你', '我')
                .replace("吗", "")
                .replace('?', '!')
                .replace('？', '！');
    }
}
